import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Tabs, Row, Select, Table, Avatar, Modal, Checkbox } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import { router } from 'umi'
import { addCat, getCatList, getAlbumList } from '@/services/goodCenter/goodsManage/goodsCat'
import AlbumUpload from '@/components/AlbumUpload'
import Asort from '@/components/sorttable/index'

const { Option } = Select

// 表头
const columns = [
  {
    title: '分类名称',
    dataIndex: 'catName',
    key: 'catName',
    align: 'center'
  },
  {
    title: '商品数量',
    dataIndex: 'countGoods',
    key: 'countGoods',
    align: 'center'
  }
]

const GoodsCat = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [total, setTotal] = useState(1)
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [record, setRecord] = useState({})
  const [catList, setCatList] = useState([])
  const [visible, setVisible] = useState(false)
  const [catParentList, setCatParentList] = useState([
    {
      id: '0',
      name: '顶级分类'
    }
  ])
  const [picList, setPicList] = useState([])  // 我的相册列表
  const [albumId, setAlbumId] = useState(0) // 默认相册id
  const [onUseSelectPhoto, setOnUseSelectPhoto] = useState(null) // 选中使用图片
  const [catIcon, setCatIcon] = useState('')
  const [catPhoneIcon, setCatPhoneIcon] = useState('')
  const [AlbumVisible, setAlbumVisible] = useState(false)
  const [uploadType, setUploadType] = useState('catIcon')

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      console.log(record)
    },
  }

  useEffect(() => {
    init()
  }, [])

  const init = async () => {
    await getCatLists()
    await getAlbumLists()
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields(async (err, values) => {
      console.log('Received values of form: ', values)

    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return(<Row></Row>)
  }
  // 按钮处理
  const handleBtn = type => {
    console.log(type)
    switch (type) {
      case 1:
        handleModal()
        break;
    }
  }

  const pagination = {
    total: parseInt(total),
    onChange(page) {
      let params = {
        pageNo: page,
        pageSize
      }
    }
  }

  const handleModal = () => {
    setVisible(!visible)
  }
  // 添加分类
  const addCats = async () => {
    form.validateFields(async (err, values) => {
      console.log('Received values of form: ', values)
      let params = {
        resGoodsCat: {
          catName: values.catName,
          catParentId: values.catParentId,
          isCanUseUniformPriceAdjustment: values.isCanUseUniformPriceAdjustment ? '1' : '2',
          catIcon: catIcon[0].props.src,
          catPhoneIcon: catPhoneIcon[0].props.src
        }
      }
      let res = await addCat(params)
      if (res.code === '0') {
        alert(res.msg)
        init()
        handleModal()
      } else {
        alert(res.msg)
      }
    })
  }
  // 获取分类列表
  const getCatLists = async () => {
    let res = await getCatList()
    if (res.code === '0') {
      setCatList(res.data)
    } else {
      alert(res.msg)
    }
  }

  const handleAlbumModal = (type) => {
    setUploadType(type)
    setAlbumVisible(!AlbumVisible)
  }

  const handleAlbumOk = () => {
    console.log('handleAlbumOk')
  }

  const handleSelectPhoto = (value) => {
    if (value.length === 0) return
    console.log(value[value.length - 1].imageUrl)
    switch (uploadType) {
      case 'catIcon':
        setCatIcon([<img src={value[value.length - 1].imageUrl} style={{ width: 100, height: 100 }} />])
        break
      case 'catPhoneIcon':
        setCatPhoneIcon([<img src={value[value.length - 1].imageUrl} style={{ width: 100, height: 100 }} />])
        break
    }
    // console.log(uploadType)
  }
  // 获取相册列表
  const getAlbumLists = async () => {
    let res = await getAlbumList()
    if (res.code === '0') {
      setPicList(res.data)
      setAlbumId(res.data[0].id)
    } else {
      alert(res.msg)
    }
  }

  return (
    <PageHeaderWrapper>
      {/* <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} /> */}
      <RenderButtom click={handleBtn} />
      <Button type="primary">全部展开</Button>
      <Button type="primary" style={{marginLeft: '6px'}}>全部收缩</Button>
      <Table
        columns={columns}
        dataSource={catList}
        rowKey={record => record.id}
        pagination={pagination}
        rowSelection={rowSelection}
      />
      <Modal
        title="添加商品分类"
        visible={visible}
        onOk={addCats}
        onCancel={handleModal}
      >
        <Row gutter={24}>
          <Col span={24}>
            <Form.Item label="分类名称" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('catName', {})
                (<Input placeholder="请输入分类名称" />)}
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label="上级分类" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('catParentId', {})
                (<Select
                  style={{ width: '100%' }}
                  showSearch
                  filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                  placeholder="请选择"
                >
                  { catParentList && catParentList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
                </Select>)}
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label="Banner图" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('catIcon', {})
                (<Asort items={catIcon} upload={() => { handleAlbumModal('catIcon') }} />)}
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label="手机端显示图" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('catPhoneIcon', {})
                (<Asort items={catPhoneIcon} upload={() => { handleAlbumModal('catPhoneIcon') }} />)}
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('isCanUseUniformPriceAdjustment', {
                valuePropName: 'checked'
              })
                (<Checkbox>是否开启统一调价模式权限</Checkbox>)}
            </Form.Item>
          </Col>
        </Row>
      </Modal>
      <Modal
        title="我的图库"
        visible={AlbumVisible}
        onOk={handleAlbumOk}
        onCancel={handleAlbumModal}
        width={1400}
      >
        <AlbumUpload
          picList={picList}
          albumId={albumId}
          onUseSelectPhoto={handleSelectPhoto}
        />
      </Modal>
   </PageHeaderWrapper>
  )
}

export default Form.create()(GoodsCat)
